import time
import hashlib
import requests
import json
import pymysql


# 通过MD5获取签名
def get_sign(p_ak, p_secret, p_millis):
    arg = p_ak + p_secret + p_millis
    res_sign = hashlib.md5(arg.encode('utf-8')).hexdigest()
    return res_sign


# 获取请求密钥
def get_requestSecret(p_response):
    dict_str = json.loads(p_response)  # 转换成json格式
    dic_data = dict_str["datas"]
    return dic_data["requestSecret"]


# 将List结果集插入数据库
def datas2mysql(p_datas):
    db = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='1234', db='test')
    cursor = db.cursor()
    res_sql = "insert into xxcx(`cc`, `rxrq`, `xxxs`, `xm`, `zsbh`, `byrq`, `zjhm`, `zymc`, `yxmc`) values(%(cc)s, %(rxrq)s, %(xxxs)s, %(xm)s, %(zsbh)s, %(byrq)s, %(zjhm)s, %(zymc)s, %(yxmc)s)"
    cursor.executemany(res_sql, p_datas)
    db.commit()


if __name__ == '__main__':
    # 在我的接口中查看所属应用，隐私管理获取所属应用AK
    ak = '***'
    secret = '***'
    # 获取当前时间戳
    millis = int(round(time.time() * 1000))
    print("millis: ", millis)
    # 获取sign
    sign = get_sign(ak, secret, str(millis))
    print("sign: ", sign)
    # 获取刷新密钥
    url = "***/gateway/app/refreshTokenByKey.htm"
    params = {"appKey": ak, "sign": sign, "requestTime": millis}
    res = requests.get(url=url, params=params)
    print(res.text)
    # 获取请求密钥
    refreshSecret = get_requestSecret(res.text)
    # 获取数据的地址
    api_url = "***"
    refreshSign = get_sign(ak, refreshSecret, str(millis))
    api_param = {"cardId": "***", "appKey": ak, "sign": refreshSign, "requestTime": millis, "additional": "附加"}
    api_res = requests.get(url=api_url, params=api_param)
    print(api_res.text)
    print('SUCCESS!')
